package com.jacky.flutter_screen_recording;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.jacky.JAlertDialog;
import com.jacky.crypto.EDA;
import com.jacky.log.Logger;

import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;

/**
 * 手机录屏-管理截图
 */
public class ShotManagerActivity extends FragmentActivity implements View.OnClickListener {

    /**屏幕录制-截图通知*/
    static final String SHOT_ACTION = "com.enotary.cloud.screen_shot.action";
    /**屏幕录制-结束通知通知*/
    static final String SCREEN_END_ACTION = "com.enotary.cloud.screen_end.action";

    /**手机录屏截图管理，screenDir 当前证据的目录*/
    public static void start(Context context,String screenDir){
        Intent intent = new Intent(context, ShotManagerActivity.class);
        intent.putExtra(Intent.EXTRA_TEXT, screenDir);
        intent.addFlags(
                Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_HISTORY
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private TextView emptyView;
    private RecyclerView recyclerView;
    private ViewPager viewPager;
    private TextView titleView;
    private View rightView;

    private ShotManagerAdapter mAdapter;
    private LargerImageAdapter mLargeAdapter;
    private File mScreenDir;
    protected File[] mData;
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent == null || intent.getAction() == null) return;
            String action = intent.getAction();
            if(SHOT_ACTION.equals(action)) {
                resetView();
            } else if(SCREEN_END_ACTION.equals(action)) {
                finish();
            }
        }
    };

    private void initView() {
        findViewById(R.id.screen_title_close).setOnClickListener(this);
        rightView = findViewById(R.id.right_icon);
        rightView.setOnClickListener(this);
        recyclerView = findViewById(R.id.recycler_view);
        viewPager = findViewById(R.id.view_pager);
        titleView = findViewById(R.id.screen_title);
        emptyView = findViewById(R.id.empty_hint_view);
        emptyView.setCompoundDrawablesWithIntrinsicBounds(null, getDrawable(), null,null);

        int dp = AppUtils.dip2px(this, 5);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int count = (int) (dm.widthPixels / dm.density / 150);
        count = Math.max(count, 3);
        int height = dm.widthPixels / count - dp;
        recyclerView.setLayoutManager(new GridLayoutManager(this, count));
        recyclerView.addItemDecoration(new GridItemDecoration(dp,dp));
        recyclerView.setAdapter(mAdapter = new ShotManagerAdapter(height));

        viewPager.setAdapter(mLargeAdapter = new LargerImageAdapter());
        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                updateTitle(position);
            }
        });
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.screen_title_close) {
            onBackPressed();
        } else if (id == R.id.right_icon) {
            JAlertDialog dialog = new JAlertDialog();
            dialog.setMessage("确定删除？\n删除后不能找回!");
            dialog.setBtnOk("删除", (dialog1, which) -> deleteShot());
            dialog.show(this);
        }
    }

    private void deleteShot(){
        if(ScreenRecordService.getService() == null) return;
        if(viewPager == null || isFinishing()) return;
        ScreenRecordService service = ScreenRecordService.getService();
        int pos = viewPager.getCurrentItem();
        File item = mAdapter.getItem(pos);

        boolean res = service.removeShot(item);
        if(res){
            mData = AppUtils.remove(mData, pos);
            emptyView.setVisibility(mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
            AppUtils.showToast(this, "删除成功");
            Logger.d("=======================current ",viewPager.getCurrentItem(),"old cur",pos);
            if(mAdapter.getItemCount() == 0) {
                resetView();
            } else {
                mAdapter.notifyDataSetChanged();
                mLargeAdapter.notifyDataSetChanged();
                updateTitle(viewPager.getCurrentItem());
            }
        } else {
            Logger.w("======================= Screen Shot delete fail");
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT); // 设置状态栏为透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        setContentView(R.layout.shot_manager_activity);
        initView();

        String dir = getIntent().getStringExtra(Intent.EXTRA_TEXT);
        if(dir == null || dir.length() == 0) return;
        File file = new File(dir);
        if(!file.exists()) return;
        //只要目录
        mScreenDir = file.isFile() ? file.getParentFile() : file;
        IntentFilter filter = new IntentFilter();
        filter.addAction(SHOT_ACTION);
        filter.addAction(SCREEN_END_ACTION);
        registerReceiver(mReceiver,filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onDestroy() {
        AppUtils.unregisterReceiver(this, mReceiver);
        super.onDestroy();
    }

    private void initData(){
        if(emptyView == null || isFinishing()) return;
        if(mScreenDir == null || !mScreenDir.exists()) {
            emptyView.setVisibility(View.VISIBLE);
            return;
        }
        mData = mScreenDir.listFiles(pathname -> pathname.getName().endsWith(".jpg"));
        if(mData != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //正序排序
            Arrays.sort(mData, Comparator.comparingLong(File::lastModified));
        }
        emptyView.setVisibility(mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
        mLargeAdapter.notifyDataSetChanged();
        mAdapter.notifyDataSetChanged();
        titleView.setText("证据管理");
    }

    private class ShotManagerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> implements AdapterView.OnItemClickListener {

        private final int itemHeight;
        private final ThumbUtils mThumbUtils;

        //展示缩略图
        private ShotManagerAdapter(int height) {
            this.itemHeight = height;
            mThumbUtils = new ThumbUtils(ShotManagerActivity.this);
        }

        private View onCreateView(ViewGroup group, int viewType) {
            ImageView iv = new ImageView(group.getContext());
            RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    itemHeight == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : itemHeight);
            iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
            iv.setLayoutParams(params);
            iv.setBackgroundResource(R.drawable.btn_blue_border_round);
            iv.setPadding(0,2,0,2);
            return iv;
        }

        private void onBindViewHolder(RecyclerViewHolder holder, File item, int position) {
            ImageView iv = (ImageView) holder.itemView;
            mThumbUtils.loadLocalFile(iv, item);
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                viewPager.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            rightView.setVisibility(View.VISIBLE);
            viewPager.setCurrentItem(position);
        }

        @NonNull
        @Override
        public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = onCreateView(parent, viewType);
            return new RecyclerViewHolder(view).setOnItemClickListener(this);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
            onBindViewHolder(holder, getItem(position), position);
        }

        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.length;
        }

        private File getItem(int position) {
            return mData == null || mData.length == 0 ? null : mData[position];
        }
    }

    private static class RecyclerViewHolder extends RecyclerView.ViewHolder {

        public RecyclerViewHolder(@NonNull View itemView) {
            super(itemView);
        }

        public RecyclerViewHolder setOnItemClickListener(@NonNull final AdapterView.OnItemClickListener listener) {
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(null, v, getLayoutPosition(), v.getId());
                }
            });
            return this;
        }
    }

    private class LargerImageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.length;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return POSITION_NONE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = getItemView(container, position);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView view = (ImageView) object;
            view.setImageBitmap(null);
            container.removeView(view);
        }
        private View getItemView(ViewGroup container, int position){
            ImageView iv = new ImageView(container.getContext());
            iv.setImageBitmap(BitmapFactory.decodeFile(mData[position].getAbsolutePath()));
            return iv;
        }
    }

    private Drawable getDrawable() {
        try {
            InputStream stream = getAssets().open("smart_refresh_empty.png");
            BitmapDrawable d = new BitmapDrawable(stream);
            d.setTargetDensity(DisplayMetrics.DENSITY_XHIGH);
            return d;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void onBackPressed() {
        if(viewPager.getVisibility() == View.VISIBLE) {
            resetView();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        resetView();
    }

    private void resetView() {
        viewPager.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
        rightView.setVisibility(View.GONE);
        initData();
    }
    private void updateTitle(int position) {
        titleView.setText(mData[position].getName());
    }
}
